#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h> 
#include <time.h>


#define LOG_TAG
#define log_xxx(format, arg...)	do { printf(LOG_TAG "[DEBUG]%d,%s--- " format "\n",\
										__LINE__,__func__, ## arg);} \
									while (0)
static int popen_test()
{
    char buff[1024] = {};

    char cmd[128] = {0};
    memset(cmd,0,sizeof(cmd));
    sprintf(cmd, "ifconfig");
    FILE *fp = popen(cmd, "r");

    if (fp != NULL)
    {
        while(NULL != fgets(buff, sizeof(buff)-1, fp)){
				printf("read %s\n",buff);
        	}
        
		pclose(fp);	
    } 
    return 0;
}

static int memopen_test()
{
    char *mem_ptr=NULL;
    size_t sizeloc=0;
    FILE *out_file=NULL;
    char buf[1024];
    memset(buf,0,sizeof(buf));
    log_xxx("fmemopen test\n");

    FILE *fp = fmemopen(buf,sizeof(buf),"w");
    if (fp != NULL)
    {
        fprintf(fp,"Line 1\n");
        fprintf(fp,"Line 2\n");
		fclose(fp);	
        fp=NULL;
    }else{
        log_xxx("fmemopen failed!\n");
    }
    out_file = fopen("fmemopen_file.txt","w+");
    if(out_file){
        fprintf(out_file,"%s",buf);
        fclose(out_file);	
        out_file=NULL;
    }

    fp =open_memstream(&mem_ptr,&sizeloc);
    if (fp != NULL)
    {
        log_xxx("open_memstream ok ptr:%p sizeloc=%lu!\n",mem_ptr,sizeloc);
        fprintf(fp,"open_memstream Line 1\n");
        fprintf(fp,"open_memstream Line 2\n");
        log_xxx("para state:ptr:%p sizeloc=%lu!\n",mem_ptr,sizeloc);//para state:ptr:(nil) sizeloc=0!

		fclose(fp);	
        fp=NULL;
    }else{
        log_xxx("open_memstream failed!\n");
    }
    out_file = fopen("open_memstream_file.txt","w+");
    if(out_file){
        fprintf(out_file,"%s",mem_ptr);
        fclose(out_file);	
        out_file=NULL;
    }
    log_xxx("before free para state:ptr:%p sizeloc=%lu!\n",mem_ptr,sizeloc);//before free para state:ptr:0xc68670 sizeloc=44!
    free(mem_ptr);




    return 0;
}


int main()
{    
    memopen_test();
    return 0;
}